<!-- user management -->
<script setup lang="ts">
import { reactive, ref, toRefs, onMounted } from 'vue';
import { ElPagination } from "element-plus"
import { Page } from '@vben/common-ui';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
dayjs.extend(utc);
import { $t } from '#/locales/index.js'
import { trimStringParams } from '#/utils/trimStringParams'
import { getUserListApi, resetUserPasswordApi } from '#/api/system/user';
import { getRolePageApi } from '#/api/system/role'

import { Query, ResetPosswordDialog, SetRoleDialog } from './modules/user';
import CustomPopover from '#/components/custom-popover.vue';
import { RotateCcwKey, Equal } from '@vben/icons';
import { useMessageBox } from '#/hooks/useMessageBox';
import { Play } from '@vben/icons';

const { confirm: confirmSubmit } = useMessageBox({})

const setRoleDialogRef = ref<InstanceType<typeof SetRoleDialog> | null>(null)
const resetPosswordDialogRef = ref<InstanceType<typeof ResetPosswordDialog> | null>(null)

const tableLoading = ref(false);
const total = ref(0)
const defaultQueryData = {
  phone: '',
  nameCn: '',
  idCard: '',
  email: '',
  isAdmin: null,
  roles: [],
  createTime: null,
}
const queryData = reactive({ ...defaultQueryData });
const tableData = ref<any>([]);
const pageData = reactive({
  curPage: 1,
  pageSize: 10,
});
const curUserData = ref()
const roleList = ref([])
const getTabelData = () => {
  console.log(123)
  const { curPage, pageSize } = toRefs(pageData)
  const params = {
    curPage: curPage.value,
    pageSize: pageSize.value
  } as any;
  const trimData = trimStringParams(queryData)
  console.log(trimData)
  Object.keys(trimData).forEach(key => {
    const kVal = trimData[key as keyof typeof trimData]
    if (kVal && key !== 'isAdmin' || key === 'isAdmin' && kVal !== null) {
      if (key === 'createTime' && Array.isArray(kVal)) {
        console.log(kVal)
        params['startTime'] = kVal[0]
        params['endTime'] = kVal[1]
      } else {
        params[key] = kVal
      }
    }
  })
  tableLoading.value = true
  getUserListApi(params)
    .then((res) => {
      const { data, pageInfo } = res;
      tableData.value = data;
      total.value = pageInfo?.totalRows
    })
    .finally(() => {
      tableLoading.value = false;
    });
};

onMounted(() => {
  getTabelData();
  getRoleList()
})


const handleSizeChange = (val: number) => {
  pageData.pageSize = val
  pageData.curPage = 1
  getTabelData()
}
const handleCurrentChange = (val: number) => {
  pageData.curPage = val
  getTabelData()
}
const resetQuery = () => {
  Object.assign(queryData, defaultQueryData)
  getTabelData()
}

const editRole = (data: any) => {
  curUserData.value = data
  setRoleDialogRef.value?.inint()
}

const resetPossword = (data: any) => {
  const message = $t('user.resetPassTipTxt');
    confirmSubmit(message).then(() => {
      tableLoading.value = true
      resetUserPasswordApi({ userId: data.userId }).then(() => {
        getTabelData()
      }).finally(() => {
        tableLoading.value = false
      })
    }).catch(() => {
      tableLoading.value = false
    })
}

const getRoleList = async () => {
  const res = await getRolePageApi({ page: 1 })
  roleList.value = res.data.filter((item: any) => item.status === 'enable') || []
}

const getRoleName = (roleIds: number[], isAll: boolean = false) => {
  const roleNames = roleIds.map((id: number) => 
    roleList.value.find((item: any) => item.id === id)
  ).filter(Boolean) as any[]
  if (roleNames.length > 0) {
    return isAll ? roleNames : roleNames[0]?.name
  } else {
    return  isAll ? [] : '--'
  }
}
</script>
<template>
  <Page class="h-full">
    <section class="flex h-full flex-col bg-[#fff] p-[24px] rounded-sm">
      <Query v-model="queryData" :roleList="roleList" class="mb-[5px]" @query-data="getTabelData" @reset-query="resetQuery" />
      <el-table :data="tableData" class="flex-1 overflow-auto" v-loading="tableLoading">
        <el-table-column align="center" width="60px" type="index"
          :label="$t('common.numberIdxTxt')" />
        <el-table-column prop="nameCn" :label="$t('user.nameTxt')" min-width="80">
          <template #default="{ row }">
            <div>{{ row.nameCn || '--' }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="idCard" :label="$t('user.idNumberTxt')" min-width="170">
          <template #default="{ row }">
            <CustomPopover :strTxt="row.idCard ?? '--'"></CustomPopover>
          </template>
        </el-table-column>
        <el-table-column prop="phone" :label="$t('common.phoneTxt')" min-width="116" />
        <el-table-column prop="email" :label="$t('common.emailTxt')" min-width="200px">
          <template #default="{ row }">
            <CustomPopover :strTxt="row.email ?? '--'"></CustomPopover>
          </template>
        </el-table-column>
        <el-table-column prop="isAdmin" :label="$t('user.userTypeTxt')" min-width="120px">
          <template #default="{ row }">
            <div>{{ row.isAdmin ? $t('user.backUserTxt') : $t('user.frontUserTxt') }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="roles" :label="$t('user.roleTxt')" min-width="150px">
          <template #default="{ row }">
            <el-popover width="200px" v-if="row.roles" trigger="hover">
              <template #reference>
                <div
                  v-if="row.roles?.length > 0"
                  class="role-name hover:text-sky-500 cursor-pointer width-auto overflow-hidden whitespace-nowrap text-ellipsis">
                  <Play fill="#595959" class="text-[#595959] play-icon scale-[0.6] inline-block align-top"></Play>
                  <span>{{ getRoleName(row.roles, false) }}</span>
                </div>
                <div v-else>--</div>
              </template>
              <template #default>
                <div>
                  <el-table :data="getRoleName(row.roles, true)">
                    <el-table-column width="60px" align="center" type="index" :label="$t('common.numberIdxTxt')" />
                    <el-table-column prop="name" min-width="80px" :label="$t('user.roleTxt')" />
                  </el-table>
                </div>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" :label="$t('common.regTimeTxt')" min-width="110px">
          <template #default="{ row }">
            <div>{{ dayjs(row.createTime).format('YYYY-MM-DD') }}</div>
          </template>
        </el-table-column>
        <el-table-column :label="$t('user.isRealNameTxt')" min-width="80px">
          <template #default="{ row }">
            <div>{{ row.isRealName ? $t('common.yesTxt') : $t('common.noTxt') }}</div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" :label="$t('common.handleTxt')" min-width="80">
          <template #default="{ row }">
            <el-tooltip effect="dark" :content="$t('user.resetPassTxt')" :show-after="1000" placement="top">
              <el-button :icon="RotateCcwKey" link @click="resetPossword(row)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" :content="$t('user.assignRolesTxt')" :show-after="1000" placement="top">
              <el-button :icon="Equal" link @click="editRole(row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <ElPagination @size-change="handleSizeChange" @current-change="handleCurrentChange" class="pagination pt-[15px]"
        size="small" layout="total, sizes, prev, pager, next, jumper" :page-sizes="[10, 20, 50, 100]"
        :page-size="pageData.pageSize" :total="total"></ElPagination>
      <SetRoleDialog :roleList="roleList" ref="setRoleDialogRef" @query-table="getTabelData" :userData="curUserData" />
      <ResetPosswordDialog ref="resetPosswordDialogRef" @query-table="getTabelData" :userData="curUserData" />
    </section>
  </Page>
</template>
<style lang="scss" scoped>
  .role-name {
    &:hover {
      .play-icon {
        transform: rotate(90deg) scale(0.6);
        transition: transform 0.2s;
      }
    }
  }
</style>
